package com.xtoad.ecms.baseinfo.controller;

import com.xtoad.ecms.common.utils.CaptchaUtils;
import com.xtoad.ecms.common.utils.TokenUtils;
import com.xtoad.ecms.common.web.annotation.PrintRequestInfo;
import com.xtoad.ecms.common.web.annotation.RequiredToken;
import com.xtoad.ecms.common.web.base.Result;
import org.apache.logging.log4j.core.config.plugins.validation.constraints.Required;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 图形验证码控制器
 *
 * @author xtoad
 * @date 2021/02/17
 */
@RestController
@RequiredToken(value = false)
@RequestMapping("captcha")
public class CaptchaController {

    public static final String TOKEN_KEY_CAPTCHA = "captcha";

    /**
     * 获取默认宽高的验证码
     *
     * @return 注册用户信息
     */
    @PrintRequestInfo
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Result<byte[]> getCaptcha(HttpServletResponse response) {
        CaptchaUtils captchaUtils = CaptchaUtils.getInstance();
        byte[] img = captchaUtils.generate();
        setHeader(captchaUtils.getCaptcha(), response);
        return Result.success(img);
    }

    /**
     * 获取指定宽高的验证码
     *
     * @return 注册用户信息
     */
    @PrintRequestInfo
    @RequestMapping(value = "", method = RequestMethod.GET)
    public Result<byte[]> getCaptcha(@Required @RequestParam("w") Integer width,
                                     @Required @RequestParam("h") Integer height,
                                     HttpServletResponse response) {
        CaptchaUtils captchaUtils = CaptchaUtils.getInstance();
        byte[] img = captchaUtils.generate(width, height, 4);
        setHeader(captchaUtils.getCaptcha(), response);
        return Result.success(img);
    }

    /**
     * 把验证码放入header
     *
     * @param captcha
     * @param response
     */
    private void setHeader(String captcha, HttpServletResponse response) {
        Map<String, String> tokenInfo = new HashMap<>(6);
        tokenInfo.put(TOKEN_KEY_CAPTCHA, captcha);
        String token = TokenUtils.generateToken(tokenInfo);
        response.setHeader("Access-Control-Expose-Headers", TokenUtils.TOKEN_HEADER);
        response.addHeader(TokenUtils.TOKEN_HEADER, token);
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
    }
}
